package com.example.study.ui.recycler

import android.content.Context
import android.view.View
import androidx.recyclerview.widget.RecyclerView

/**
 *  created by 20300
 *   on 2022/3/25
 *   describe:梯形,堆叠
 */
class EchelonLayoutManager(): RecyclerView.LayoutManager() {
    lateinit var mContext:Context
    var mItemViewHeight:Int = 0
    var mItemViewWidth:Int = 0
    var mItemCount:Int = 0
    var mScrollOffset:Int = 0
    var mScale:Float = 0.9f

    constructor(context: Context):this(){
        this.mContext = context
        mItemViewWidth = (getHorizontalSpace()*0.87f).toInt()
        mItemViewHeight = (mItemViewWidth*1.46f).toInt()
    }
    override fun generateDefaultLayoutParams(): RecyclerView.LayoutParams {
        return RecyclerView.LayoutParams(
            RecyclerView.LayoutParams.WRAP_CONTENT,
            RecyclerView.LayoutParams.WRAP_CONTENT
        )
    }

    override fun onLayoutChildren(recycler: RecyclerView.Recycler?, state: RecyclerView.State?) {
        //super.onLayoutChildren(recycler, state)
        if (state?.itemCount==0|| state?.isPreLayout == true){
            return
        }
        removeAndRecycleAllViews(recycler!!)
        mItemViewWidth =(getHorizontalSpace()*0.87f).toInt()
        mItemViewHeight =(getHorizontalSpace()*1.46f).toInt()
        mItemCount = itemCount
        mScrollOffset = Math.min(Math.max(mItemViewHeight,mScrollOffset),mItemCount*mItemViewHeight)
        layoutChild(recycler)
    }

    private fun layoutChild(recycler: RecyclerView.Recycler) {
        if (itemCount == 0) return
        var bottomItemPosition = Math.floor((mScrollOffset/mItemViewHeight).toDouble()).toInt()
        var remainSpace = getVerticalSpace() - mItemViewHeight
        var bottomItemVisibleHeight = mScrollOffset%mItemViewHeight
        val offsetPercentRelativeToItemView = bottomItemVisibleHeight*1.0f/mItemViewHeight
        var layoutInfos = mutableListOf<ItemViewInfoBean>()
        run {
            var i: Int = bottomItemPosition - 1
            var j = 1
            while (i >= 0) {
                i--
                j++
            }
        }
    }

    /*获取RecyclerView的显示宽度*/
    fun getHorizontalSpace():Int{
        return width-paddingLeft-paddingRight
    }
    /*获取RecyclerView的显示高度*/
    fun getVerticalSpace():Int{
        return width-paddingLeft-paddingRight
    }

    /*测量itemView的确切大小*/
    fun measureChildWidthExactlySize(child:View){
        var widthSpec = View.MeasureSpec.makeMeasureSpec(mItemViewWidth,View.MeasureSpec.EXACTLY)
        var heightSpec = View.MeasureSpec.makeMeasureSpec(mItemViewHeight,View.MeasureSpec.EXACTLY)
        child.measure(widthSpec,heightSpec)
    }
}